<script setup>
import { nextTick, ref, onMounted, computed, onBeforeMount, watch } from 'vue';
import MostHeader from '@/components/MostHeader.vue';
import MessageCard from "@/views/messageBox/components/MessageCard.vue";
import MessageInput from "@/views/messageBox/components/MessageInput.vue";
import MessageBubble from "@/views/messageBox/components/MessageBubble.vue";
import MessageHeader from "@/views/messageBox/components/MessageHeader.vue";
import {getAllMessage, readMessage} from "@/api/message.js";
import { updateMessage } from "@/views/messageBox/components/share.js";
import { messageStore } from "@/stores/modules/messageStore.js";
import { userUserStore } from "@/stores/index.js";
import { useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { companyInfoStore } from "@/stores/modules/companyInfo.js";
import { companyMessageStore } from "@/stores/modules/compantMessage.js";
import { jobMessageStore } from "@/stores/modules/jobMessage.js";

const contacts = ref('');
const chatContainer = ref(null);
const selectedContact = ref(null);
const route = useRoute();
const currentSessionId = ref(route.query.chatSessionId);
const updatedMessages = ref(messageStore().messageInfo);
const searchQuery = ref('');
const nowRole = ref('')
const isLoading = ref(false)

// 默认就到最底部
onBeforeMount(async () => {
  isLoading.value = true
  await updateMessage().then(() => {
    contacts.value = messageStore().messageInfo
    nowRole.value = messageStore().nowRole
  }).catch(err =>{
    message.error('系统异常，请尝试刷新页面')
  })
  isLoading.value = false

  if (currentSessionId.value) {
    selectedContact.value = contacts.value.find(item => String(item.sessionId) === String(currentSessionId.value));
  } else {
    selectedContact.value = contacts.value[0];
  }

  nextTick(() => {
    scrollToBottom();
  });
});

onMounted(() => {
  setInterval(fetchMessages, 5000); // 每5秒获取最新消息
});

const fetchMessages = async () => {
  const res = await getAllMessage();
  updatedMessages.value = res.data.data?.chatSessions;
  syncMessages(updatedMessages.value);
};


const syncMessages = (updatedContacts) => {
  updatedContacts.forEach((updatedContact) => {
    const existingContact = contacts.value.find(item => item.sessionId === updatedContact.sessionId);

    if (existingContact) {
      // 更新新的消息记录
      if (updatedContact.messages.length > existingContact.messages.length) {
        existingContact.messages = updatedContact?.messages;
        scrollToBottom();
      }
      // 更新其他可变信息，例如最后更新时间
      existingContact.updateTime = updatedContact?.updateTime;
      existingContact.unRead = updatedContact?.unRead;
    } else {
      // 新增的联系人
      contacts.value = [...updatedContacts];
    }
  });
};

const scrollToBottom = () => {
  if (chatContainer.value) {
    // 使用 nextTick 确保 DOM 更新后再执行滚动
    nextTick(() => {
      const start = chatContainer.value?.scrollTop;
      const end = chatContainer.value?.scrollHeight;
      const distance = end - start;

      // 动态调整动画持续时间
      const baseDuration = 100; // 基础持续时间
      const duration = Math.min(800, Math.max(baseDuration, (distance / 200) * baseDuration)); // 最长时间限制为1000ms

      let startTime;

      const scrollStep = (timestamp) => {
        if (!startTime) startTime = timestamp;
        const progress = timestamp - startTime;
        const easing = (progress / duration) ** 2; // 平滑滚动（缓动效果）

        chatContainer.value.scrollTop = start + distance * easing;

        if (progress < duration) {
          requestAnimationFrame(scrollStep);
        } else {
          chatContainer.value.scrollTop = end; // 确保滚动到底部
        }
      };
      requestAnimationFrame(scrollStep);
    });
  }
};

// 选择联系人
const selectContact = async (item) => {
  selectedContact.value = item;
  console.log(item)
  selectedContact.value.unRead = 0
  readMessage(item.sessionId)
  scrollToBottom()
};

// 处理消息发送成功的回调函数
const handleMessageSent = () => {
  fetchMessages();
};

// 计算属性：根据搜索内容过滤联系人
const filteredContacts = computed(() => {
  if(searchQuery.value === '') {
    return contacts.value
  }
  if(nowRole.value === 'student') {
    return contacts.value.filter(contact => {
      const searchText = searchQuery?.value.toLowerCase();
      console.log (searchText)
      return contact.companyInfo.companyName?.toLowerCase().includes(searchText) ||
          contact.jobInfo.jobName?.toLowerCase().includes(searchText) ||
          contact.messages.some(msg => msg.content?.toLowerCase().includes(searchText));
    });
  }else {
    return contacts.value.filter(contact => {
      const searchText = searchQuery.value.toLowerCase();
      return contact.stuInfo.username?.toLowerCase().includes(searchText) ||
          contact.messages.some(msg => msg.content?.toLowerCase().includes(searchText));
    });
  }
});
</script>

<template>
  <div class="chat-page"  v-loading.fullscreen.lock="isLoading"
       element-loading-text="正在加载..."
       element-loading-background="transparent">
    <!-- 顶部导航栏 -->
    <MostHeader />
    <!-- 主体布局 -->
    <a-layout class="contact-container" hasSider>
      <!-- 左侧联系人列表 -->
      <a-layout-sider width="360" class="contact-list">
        <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索30天内的联系人"
            class="search-input"
        />
        <!--        <div class="tabs">-->
        <!--          <span-->
        <!--              v-for="tab in ['全部', '新招呼', '仅沟通', '有交换']"-->
        <!--              :key="tab"-->
        <!--              @click="selectTab(tab)"-->
        <!--              :class="{ 'tab-item': true, 'tab-item-selected': selectedTab === tab }">-->
        <!--            {{ tab }}-->
        <!--          </span>-->
        <!--        </div>-->
        <a-list :data-source="filteredContacts" bordered :split="false" item-layout="horizontal" class="contact-list-content">
          <template #renderItem="{ item }">
            <a-list-item @click="selectContact(item)"
                         :class="{ 'contact-list-item': true, 'contact-list-item-selected': selectedContact?.sessionId === item.sessionId }">
              <MessageCard
                  :user-info="(nowRole === 'company')? item?.stuInfo: item?.companyInfo"
                  :job-info="(nowRole === 'company')? '': item?.jobInfo"
                  :time="item?.updateTime"
                  :unread-count="item?.unRead"
                  :content="item.messages[item.messages.length-1]?.content" />
            </a-list-item>
          </template>
        </a-list>
      </a-layout-sider>

      <!-- 中间聊天显示区域 -->
      <a-layout-content class="chat-content">
        <div class="chat-header">
          <MessageHeader
              :now-role="nowRole"
              :user-info="(nowRole === 'company')? selectedContact?.stuInfo: selectedContact?.companyInfo"
              :job-info="(nowRole === 'company')? '': selectedContact?.jobInfo"
          />
        </div>
        <div class="chat-record" ref="chatContainer">
          <MessageBubble
              v-for="(item, index) in selectedContact?.messages"
              :key="index"
              :message="item"
              :user-info="(item.senderRole === 'student')? selectedContact?.stuInfo: selectedContact?.companyInfo"
              :job-info="(item.senderRole === 'student')? '': selectedContact?.jobInfo"
              :prevTime="selectedContact?.messages[index-1]?.sentTime" />
        </div>
        <!-- 下面消息输入区域 -->
        <a-layout-footer class="message-input">
          <MessageInput
              :session-id="selectedContact?.sessionId"
              @message-sent="handleMessageSent"
              :now-role="nowRole"
              :job-info="(nowRole === 'company')? '': selectedContact?.jobInfo"/>
        </a-layout-footer>
      </a-layout-content>
    </a-layout>
  </div>
</template>

<style scoped>
.chat-page {
  height: 100%;
  width: 100%;
  background-color: #e6f7ff;
  position: absolute;
}

.chat-record {
  overflow-y: auto;
  height: 650px;
  padding: 0 20px;
}

.contact-container {
  margin: 15px auto;
  width: 1184px;
  height: calc(100% - 140px);
  border-radius: 10px;
  background-color: #e6f7ff;
}

.navbar-links span {
  margin-left: 20px;
  cursor: pointer;
}

.contact-list {
  border: 0;
  flex: 1;
  overflow-y: auto;
  overflow-x: visible;
  background-color: white;
  scrollbar-width: none;
  padding-left: 10px;
  border-radius: 10px;
}

.search-input {
  width: 90%;
  padding-left: 20px;
  margin-top: 15px;
  margin-left: 15px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  height: 30px;
}

.tabs {
  display: flex;
  justify-content: space-between;
  margin: 20px 20px 0 15px;

  >span {
    border-radius: 5px;
  }
}

.tab-item {
  padding: 5px 10px;
  background-color: #f8f8f8;
  cursor: pointer;
  transition: background-color 0.3s;
}

.tab-item:hover,
.tab-item-selected {
  background-color: #e5f8f8;
  color: #00a6a7;
}

.contact-list-content {
  margin-top: 20px;
  border: 0;
}

.chat-content {
  display: flex;
  flex-direction: column;
  padding: 20px 0 20px 0;
  background-color: #ffffff;
  margin-left: 10px;
  border-radius: 10px;
}

.message-input {
  height: 160px;
  padding: 10px;
  background-color: white;
}

.message-input input {
  flex: 1;
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}

.message-input button {
  margin-left: 10px;
  padding: 5px 10px;
  background-color: #1abc9c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.contact-list-item {
  margin: 5px;
  border-radius: 10px;
  padding: 4px;
}

.contact-list-item:hover {
  background-color: #f8f8f8;
  border-radius: 10px;
  padding: 4px;
}

.contact-list-item-selected {
  background-color: #f2f2f2;
}
</style>
